package com.dhh.nutrition.activity;

import greendroid.app.GDActivity;
import greendroid.widget.ActionBarItem.Type;
import java.util.ArrayList;
import java.util.List;
import com.dhh.nutrition.R;
import com.dhh.nutrition.dao.DataBaseHelper;
import com.dhh.nutrition.manager.FoodManager;
import com.dhh.nutrition.vo.Food;
import com.dhh.nutrition.widget.AmazingAdapter;
import com.dhh.nutrition.widget.AmazingListView;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Pair;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class NutritionDetailActivity extends GDActivity {
	private FoodManager fManager;
	private AmazingListView lsComposer;
	private DataBaseHelper db;
	private Food food;
	private int type = 0;
	private int serving = 100;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setActionBarContentView(R.layout.nutrition_detail);
        
        db = new DataBaseHelper(getBaseContext());
        db.openDataBase();        
        fManager = new FoodManager(db);
        
        if(getIntent().getExtras().getInt("serving")>0){
        	type = getIntent().getExtras().getInt("type");
        	serving = getIntent().getExtras().getInt("serving");
        }
        
        initActionBar();
    }
	
	@Override
	public void onStart(){
		super.onStart();		
		
		food = fManager.getFood(getIntent().getExtras().getString("foodNo"));
		food.setType(type);
		food.setServing(serving);
				
		fillData();
	}
	
	@Override
	protected void onPause(){
		super.onPause();
		if (db != null) {
			db.close();
		}
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.add(0, 0, 0, "100 g");
		if(food.getGmWt_1()>0)
			menu.add(0, 1, 0, food.getGmWt_Desc1()+" ("+food.getGmWt_1()+"g)");
		if(food.getGmWt_2()>0)
			menu.add(0, 2, 0, food.getGmWt_Desc2()+" ("+food.getGmWt_2()+"g)");
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case 0:
			food.setType(0);
			food.setServing(100);
			this.fillData();
			return true;
		case 1:
			food.setType(1);
			food.setServing(1);
			this.fillData();
			return true;
		case 2:
			food.setType(2);
			food.setServing(1);
			this.fillData();
			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}
	
	public void initActionBar(){
		getActionBar().setTitle("Nutrition Detail");
        getActionBar().setBackgroundColor(Color.rgb(154, 205, 50));
        getActionBar().getChildAt(0).
        	setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(NutritionDetailActivity.this,HomeActivity.class);
					startActivity(intent);
				}});
        getActionBar().addItem(Type.Gallery).getItemView().setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(NutritionDetailActivity.this,NutritionFactsActivity.class);
				intent.putExtra("foodNo", getIntent().getExtras().getString("foodNo"));
				intent.putExtra("type", food.getType());
				intent.putExtra("serving", food.getServing());
				startActivity(intent);
			}});
        
        getActionBar().addItem(Type.Edit).getItemView().setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				registerForContextMenu( v ); 
				v.setLongClickable(false);
				NutritionDetailActivity.this.openContextMenu(v);
			}});
	}
	
	public void fillData(){
		if(food.getType() == 0){
			((TextView)this.findViewById(R.id.nd_food_name)).setText(food.getShrt_Desc()+" (100g)");
		}else{
			((TextView)this.findViewById(R.id.nd_food_name)).setText(food.getShrt_Desc()+ " ("+food.getValueByType()+" "+food.getUnitMapValue()+"g)");
		}
		
		
		lsComposer = (AmazingListView) findViewById(R.id.lsComposer);
		lsComposer.setDivider( null );
		lsComposer.setDividerHeight(1); 
		lsComposer.setPinnedHeaderView(LayoutInflater.from(this).inflate(R.layout.item_composer_header, lsComposer, false));
		lsComposer.setAdapter(new SectionComposerAdapter());
	}
	
	private List<Pair<String, List<ListItem>>> getAllData(){
		List<Pair<String, List<ListItem>>> data = new ArrayList<Pair<String, List<ListItem>>>();			
		
		String proximates = "Proximates";
		List<ListItem> proximatesLst = new ArrayList<ListItem>();
		proximatesLst.add(new ListItem("Water",String.valueOf(food.getWater()),"g"));
		proximatesLst.add(new ListItem("Energy",String.valueOf(food.getEnerg_Kcal()),"kcal"));
		proximatesLst.add(new ListItem("Protein",String.valueOf(food.getProtein()),"g"));
		proximatesLst.add(new ListItem("Total lipid (fat)",String.valueOf(food.getLipid_Tot()),"g"));
		proximatesLst.add(new ListItem("Carbohydrate, by difference",String.valueOf(food.getCarbohydrt()),"g"));
		proximatesLst.add(new ListItem("Fiber, total dietary",String.valueOf(food.getFiber_TD()),"g"));
		proximatesLst.add(new ListItem("Sugars, total",String.valueOf(food.getSugar_Tot()),"g"));
		data.add(new Pair(proximates,proximatesLst));
		
		String minerals = "Minerals";
		List<ListItem> mineralsLst = new ArrayList<ListItem>();
		mineralsLst.add(new ListItem("Calcium, Ca",String.valueOf(food.getCalcium()),"mg"));
		mineralsLst.add(new ListItem("Iron, Fe",String.valueOf(food.getIron()),"mg"));
		mineralsLst.add(new ListItem("Magnesium, Mg",String.valueOf(food.getMagnesium()),"mg"));
		mineralsLst.add(new ListItem("Phosphorus, P",String.valueOf(food.getPhosphorus()),"mg"));
		mineralsLst.add(new ListItem("Potassium, K",String.valueOf(food.getPhosphorus()),"mg"));
		mineralsLst.add(new ListItem("Sodium, Na",String.valueOf(food.getSodium()),"mg"));
		mineralsLst.add(new ListItem("Zinc, Zn",String.valueOf(food.getZinc()),"mg"));
		data.add(new Pair(minerals,mineralsLst));
		
		String vitamins = "Vitamins";
		List<ListItem> vitaminsLst = new ArrayList<ListItem>();
		vitaminsLst.add(new ListItem("Vitamin C, total ascorbic acid",String.valueOf(food.getVit_C()),"mg"));
		vitaminsLst.add(new ListItem("Thiamin",String.valueOf(food.getThiamin()),"mg"));
		vitaminsLst.add(new ListItem("Riboflavin",String.valueOf(food.getRiboflavin()),"mg"));
		vitaminsLst.add(new ListItem("Niacin",String.valueOf(food.getNiacin()),"mg"));
		vitaminsLst.add(new ListItem("Vitamin B-6",String.valueOf(food.getVit_B6()),"mg"));
		vitaminsLst.add(new ListItem("Folate, DFE",String.valueOf(food.getFolate_DFE()),"mcg_DFE"));
		vitaminsLst.add(new ListItem("Vitamin B-12",String.valueOf(food.getVit_B12()),"µg"));
		vitaminsLst.add(new ListItem("Vitamin A, RAE",String.valueOf(food.getVit_A_RAE()),"mcg_RAE"));
		vitaminsLst.add(new ListItem("Vitamin A, IU",String.valueOf(food.getVit_A_IU()),"IU"));
		vitaminsLst.add(new ListItem("Vitamin E (alpha-tocopherol)",String.valueOf(food.getVit_E()),"mg"));
		vitaminsLst.add(new ListItem("Vitamin D (D2 + D3)",String.valueOf(food.getVit_D_mcg()),"µg"));
		vitaminsLst.add(new ListItem("Vitamin D",String.valueOf(food.getViVit_D_IU()),"IU"));
		vitaminsLst.add(new ListItem("Vitamin K (phylloquinone)",String.valueOf(food.getVit_K()),"µg"));
		data.add(new Pair(vitamins,vitaminsLst));
		
		String lipids = "Lipids";
		List<ListItem> lipidsLst = new ArrayList<ListItem>();
		vitaminsLst.add(new ListItem("Fatty acids, total saturated",String.valueOf(food.getFA_Sat()),"g"));
		vitaminsLst.add(new ListItem("Fatty acids, total monounsaturated",String.valueOf(food.getFA_Mono()),"g"));
		vitaminsLst.add(new ListItem("Fatty acids, total polyunsaturated",String.valueOf(food.getFA_Poly()),"g"));
		vitaminsLst.add(new ListItem("Cholesterol",String.valueOf(food.getCholestrl()),"g"));
		data.add(new Pair(lipids,lipidsLst));
		
		return data;
	}
	
	class SectionComposerAdapter extends AmazingAdapter {
		List<Pair<String, List<ListItem>>> all = getAllData();

		@Override
		public int getCount() {
			int res = 0;
			for (int i = 0; i < all.size(); i++) {
				res += all.get(i).second.size();
			}
			return res;
		}

		@Override
		public ListItem getItem(int position) {
			int c = 0;
			for (int i = 0; i < all.size(); i++) {
				if (position >= c && position < c + all.get(i).second.size()) {
					return all.get(i).second.get(position - c);
				}
				c += all.get(i).second.size();
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		protected void onNextPageRequested(int page) {
		}

		@Override
		protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
			if (displaySectionHeader) {
				view.findViewById(R.id.header).setVisibility(View.VISIBLE);
				TextView lSectionTitle = (TextView) view.findViewById(R.id.header);
				lSectionTitle.setText(getSections()[getSectionForPosition(position)]);
			} else {
				view.findViewById(R.id.header).setVisibility(View.GONE);
			}
		}

		@Override
		public View getAmazingView(int position, View convertView, ViewGroup parent) {
			View res = convertView;
			if (res == null) res = getLayoutInflater().inflate(R.layout.item_composer, null);
			TextView name = (TextView) res.findViewById(R.id.fd_name);
			TextView quatity = (TextView) res.findViewById(R.id.fd_quatity);
			TextView unit = (TextView) res.findViewById(R.id.fd_unit);
			
			ListItem item = getItem(position);
			name.setText(item.getName());
			quatity.setText(item.getQuatity());
			unit.setText(item.getUnit());
			
			return res;
		}

		@Override
		public void configurePinnedHeader(View header, int position, int alpha) {
			TextView lSectionHeader = (TextView)header;
			lSectionHeader.setText(getSections()[getSectionForPosition(position)]);
			lSectionHeader.setBackgroundColor(Color.rgb(173, 255, 47));
			lSectionHeader.setTextColor(alpha << 24 | (0x000000));
		}

		@Override
		public int getPositionForSection(int section) {
			if (section < 0) section = 0;
			if (section >= all.size()) section = all.size() - 1;
			int c = 0;
			for (int i = 0; i < all.size(); i++) {
				if (section == i) { 
					return c;
				}
				c += all.get(i).second.size();
			}
			return 0;
		}

		@Override
		public int getSectionForPosition(int position) {
			int c = 0;
			for (int i = 0; i < all.size(); i++) {
				if (position >= c && position < c + all.get(i).second.size()) {
					return i;
				}
				c += all.get(i).second.size();
			}
			return -1;
		}

		@Override
		public String[] getSections() {
			String[] res = new String[all.size()];
			for (int i = 0; i < all.size(); i++) {
				res[i] = all.get(i).first;
			}
			return res;
		}		
	}
	
	class ListItem{
		private String name;
		private String quatity;
		private String unit;
		
		public ListItem(String name,String quatity,String unit){
			this.name = name;
			this.quatity = quatity;
			this.unit = unit;
		}
		
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getQuatity() {
			return quatity;
		}
		public void setQuatity(String quatity) {
			this.quatity = quatity;
		}
		public String getUnit() {
			return unit;
		}
		public void setUnit(String unit) {
			this.unit = unit;
		}
	}
	
	
}
